package com.zen.demo.sys.type;

import com.zen.demo.common.util.SpringContentUtil;
import com.zen.demo.sys.entity.User;
import com.zen.demo.sys.mapper.UserMapper;
import org.apache.ibatis.annotations.Case;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author alexzshl
 * @since 2022/1/28 22:04
 */
@MappedJdbcTypes({JdbcType.INTEGER, JdbcType.BIGINT, JdbcType.VARCHAR})
@MappedTypes({User.class})
public class UserTypeHandler extends BaseTypeHandler<User> {
    // private static UserMapper userMapper = SpringContentUtil.getBean(UserMapper.class);

    @Override
    public void setNonNullParameter(PreparedStatement ps, int index, User user, JdbcType jdbcType) throws SQLException {
        // UserMapper userMapper = SpringContentUtil.getBean(UserMapper.class);
        System.out.println(jdbcType);
        ps.setInt(index, user.getId());
        // switch (jdbcType) {
        //     case INTEGER:
        //         ps.setInt(index, user.getId());
        //     case BIGINT:
        //         ps.setInt(index, user.getId());
        //     case VARCHAR:
        //         ps.setString(index, String.valueOf(user.getId()));
        //     case DECIMAL:
        //         throw new SQLException();
        // }
    }

    @Override
    public User getNullableResult(ResultSet resultSet, String s) throws SQLException {
        UserMapper userMapper = SpringContentUtil.getBean(UserMapper.class);
        int userId = resultSet.getInt(s);
        User user = userMapper.selectById(userId);
        return user;
    }

    @Override
    public User getNullableResult(ResultSet resultSet, int i) throws SQLException {
        UserMapper userMapper = SpringContentUtil.getBean(UserMapper.class);
        int userId = resultSet.getInt(i);
        User user = userMapper.selectById(userId);
        return user;
    }

    @Override
    public User getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        UserMapper userMapper = SpringContentUtil.getBean(UserMapper.class);
        int userId = callableStatement.getInt(i);
        User user = userMapper.selectById(userId);
        return user;
    }
}
